/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

@ManagedBean
@SessionScoped
public class DaoUsers implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3048577798999080410L;
	private int custID;
	private String name;
	private String phone;

	Connection c;
	Statement st;

	@PostConstruct
	public void init (){
		System.out.println("@PostConstruct");
		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/Dynamic");

			c = ds.getConnection();
			st = c.createStatement();
		} catch (NamingException ex) {
			Logger.getLogger(DaoUsers.class.getName()).log(Level.SEVERE, null, ex);
		} catch (SQLException ex) {
			Logger.getLogger(DaoUsers.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public int getCustID() {
		return custID;
	}

	public void setCustID(int custID) {
		this.custID = custID;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	@PreDestroy
	public void close () {
		System.out.println("PreDestroy");
		try {
			if (c != null && !c.isClosed())
				c.close();
			if (st != null && !st.isClosed())
				st.close();
		} catch (SQLException ex) {
			Logger.getLogger(DaoUsers.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public String getUserType(String name, String password) throws SQLException {
		String type = null;
		ResultSet rs = null;
		try {
			rs = st.executeQuery(
					"SELECT * " +
							"FROM USERS " +
							"WHERE username = '" + name + "' " +
							"AND password = '" + password + "'"
					);
		} catch (SQLException ex) {
			Logger.getLogger(DaoUsers.class.getName()).log(Level.SEVERE, null, ex);
		}
		type = rs.getString(3);

		return type;
	}
}
